package com.klun.concTrueWar.seven;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.concurrent.*;

/**
 * 这个类 出现死锁 类有问题 跳过 TODO
 */
public class LogService1 {
    // 单线程的 Executor
    private final ExecutorService exec =  Executors.newSingleThreadExecutor();

    private final BlockingQueue<String> queue = new LinkedBlockingDeque<>();
    private final LoggerThread loggerThread = new LoggerThread();
    private final PrintWriter writer = new PrintWriter("E:\\klun\\文档\\TJY\\WHM.txt");
    private boolean isShutdown = false;
    private int reservations = 0;

    public LogService1() throws FileNotFoundException {
    }

    public void start(){
        loggerThread.start();
    }
    public void stop() throws InterruptedException {
        try {
            exec.shutdown();
            exec.awaitTermination(10, TimeUnit.SECONDS);
        } finally {
            writer.close();
        }
    }
    public void log(String msg) {
        try {
            exec.execute(loggerThread);
        } catch (RejectedExecutionException e){
        }

    }
    class LoggerThread extends Thread{
        @Override
        public void run() {
            try{
                while (true){
                    try{
                        //  类上加锁
                        synchronized (LogService1.this){
                            if(isShutdown && reservations == 0){
                                break;
                            }
                            String msg = queue.take();
                            synchronized (LogService1.this){
                                --reservations;
                            }
                            writer.print(msg);
                        }
                    } catch (InterruptedException e) {
                        // 重新尝试
                        e.printStackTrace();
                    }

                }
            }finally {
                writer.close();
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException, InterruptedException {
        LogService1 logService1 = new LogService1();
        logService1.start();
        logService1.log("what are you doing here");
        logService1.stop();

    }
}
